<template>
	<div class="container-wrap">
		<description logo="iconfont icon-cunchujuan" :title="title" :desc="desc" />
		<el-card class="table-wrap" shadow="never">
			<div class="operation mb15">
				<div class="flex">
					<el-input clearable v-model="searchInput" @keyup.enter="search" placeholder="请输入名称" class="width-150 mr10"></el-input>
					<el-select
						v-model="storagePool"
						class="width-150 mr10"
						placeholder="选择元数据池"
						:loading='storageLoading'
					>
						<el-option
							v-for="item in storagePoolOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
					<el-button type="primary" @click="search">搜索</el-button>
				</div>
				<div>
					<el-button type="primary" @click="useGuide" :disabled="!state.table.currentRow">使用向导</el-button>
					<el-button type="primary" @click="createVolume">创建</el-button>
					<el-button type="danger" @click="delVolume" :disabled="!state.table.currentRow">删除</el-button>
					<el-button type="primary" @click="changeVolumeSize" :disabled="!state.table.currentRow">扩/缩容</el-button>
					<el-button type="primary" @click="refresh">刷新</el-button>
				</div>
			</div>
			<el-table
				ref="tableRef"
				border
				v-loading="state.table.loading"
				element-loading-text="数据加载中..."
				:data="state.table.data"
				highlight-current-row
				height="calc(100vh - 455px)"
				@current-change="handleCurrentChange"
			>
				<el-table-column prop="rbdName" label="名称" min-width="130" show-overflow-tooltip />
				<el-table-column prop="poolName" label="元数据池" min-width="130" show-overflow-tooltip />
				<el-table-column prop="dataPoolName" label="数据池" min-width="130" show-overflow-tooltip />
				<el-table-column prop="usedSize" label="存储用量" min-width="100" show-overflow-tooltip>
					<template #default="{row}">
						{{ formatUnits(row.usedSize) }}
					</template>
				</el-table-column>
				<el-table-column prop="totalSize" label="存储容量" min-width="100" show-overflow-tooltip>
					<template #default="{row}">
						{{ formatUnits(row.totalSize) }}
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:current-page="state.table.params.pageNum"
				v-model:page-size="state.table.params.pageSize"
				@current-change="onHandleCurrentChange"
				@size-change="onHandleSizeChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30, 50]"
				background
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.table.total"
			>
			</el-pagination>
		</el-card>

		<el-dialog title="存储卷使用向导" v-model="volumeGuideVisible" :destroy-on-close="true" width="1000px">
			<VolumeGuide ref="createVolumeRef" v-model:value="volumeGuideVisible" :data="state.table.currentRow"></VolumeGuide>
		</el-dialog>

		<el-dialog title="创建存储卷" v-model="createVolumeVisble" :destroy-on-close="true" width="600px">
			<CreateVolume ref="createVolumeRef" v-model:value="createVolumeVisble"></CreateVolume>
			<template #footer>
				<el-button @click="createVolumeVisble = false">取消</el-button>
				<el-button type="primary" @click="handleCreateVolume">确定</el-button>
			</template>
		</el-dialog>

		<el-dialog title="存储卷扩/缩容" v-model="changeVolumeSizeVisible" :destroy-on-close="true" width="600px">
			<ChangeVolumeSize ref="changeVolumeSizeRef" v-model:value="changeVolumeSizeVisible" :volumeInfo="state.table.currentRow"></ChangeVolumeSize>
			<template #footer>
				<el-button @click="changeVolumeSizeVisible = false">取消</el-button>
				<el-button type="primary" @click="handleChangeVolumeSize">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref, toRefs, getCurrentInstance, onMounted, onUnmounted, watch, defineAsyncComponent } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { SelectOptionItem } from '/@/types/index';
import { useStorageApi } from '/@/api/storage';
import { useBlockStorageApi } from '/@/api/block-storage/index';
import { formatUnits } from '/@/utils/other';

export interface VolumeTableRow{
	id:number,
	poolName:string,
	rbdName:string,
	totalSize:string,
	usedSize:string,
	dataPoolName:string
}
interface VolumeTableState{
	table:{
		data:VolumeTableRow[],
		loading:boolean,
		params:{
			searchName:string,
			pageNum:number,
			pageSize:number
		},
		total:number,
		currentRow: VolumeTableRow | null | undefined,
	}
}

const description = defineAsyncComponent(() => import('/@/components/description/index.vue'));
const VolumeGuide = defineAsyncComponent(() => import('./components/volumeGuide.vue'));
const CreateVolume = defineAsyncComponent(() => import('./components/createVolume.vue'));
const ChangeVolumeSize = defineAsyncComponent(() => import('./components/changeVolumeSize.vue'));

const title = '存储卷';
const desc = '存储卷将存储池中的对象映射为块设备，适用于需要高性能、高可靠性、高可用性的虚拟化和容器化应用程序';
const timer = ref();
const tableRef = ref();
const storagePool = ref('');
const storagePoolOptions = ref<SelectOptionItem[]>([]);
const searchInput = ref('');

let storageLoading = ref(true);

const state = reactive<VolumeTableState>({
	table: {
		data: [],
		loading: true,
		params: {
			searchName: '',
			pageNum: 1,
			pageSize: 10
		},
		total: 0,
		currentRow: null,
	}
});

const initTable = async (refresh:boolean = false) => {
	await useStorageApi().getPoolList({ 'fileSystem': '', 'pageNo': 1, 'pageSize': 100, poolType: '1' }).then(res => {
		storagePoolOptions.value = res.data.records.map((item:any) => {
			return {
				value: item.poolName,
				label: item.poolName
			};
		});
		storagePoolOptions.value.unshift({
			value: '',
			label: '所有元数据池'
		});
	});
	getVolumeList(refresh);
};

onMounted(() => {
	initTable(true);
});

onUnmounted(() => {
	clearInterval(timer.value);
});

const getVolumeList = (refresh:boolean = false) => {
	refresh && (state.table.loading = true);
	refresh && tableRef.value?.setCurrentRow();
	useBlockStorageApi().getVolumeList({
		pageNo: state.table.params.pageNum,
		pageSize: state.table.params.pageSize,
		poolName: storagePool.value === '' ? undefined : storagePool.value,
		rbdName: state.table.params.searchName === '' ? undefined : state.table.params.searchName
	}).then((res:any) => {
		state.table.data = res.data.records;
		state.table.total = res.data.total;
		tableRef.value?.setCurrentRow(state.table.data.find(item => item.rbdName === state.table.currentRow?.rbdName));
	}).catch(() => {
		state.table.data = [];
	}).finally(() => {
		state.table.loading = false;
		storageLoading.value = false;
	});
};

const search = () => {
	state.table.params.searchName = searchInput.value;
	getVolumeList(true);
};
const refresh = () => {
	state.table.params.searchName = searchInput.value;
	getVolumeList(true);
};
const handleCurrentChange = (currentRow:VolumeTableRow) => {
	state.table.currentRow = currentRow;
};
const onHandleCurrentChange = () => {
	state.table.params.searchName = searchInput.value;
	getVolumeList(true);
};
const onHandleSizeChange = () => {
	state.table.params.pageNum = 1;
	state.table.params.searchName = searchInput.value;
	getVolumeList(true);
};

watch(
	storagePool,
	() => {
		getVolumeList(true);
	}
);

// ws refresh list
const { proxy } = <any>getCurrentInstance();
proxy.mittBus.on('refresh-list', () => {
	getVolumeList(true);
});
onUnmounted(() => {
	proxy.mittBus.off('refresh-list');
});

// use guide
const volumeGuideVisible = ref(false);
const useGuide = () => {
	volumeGuideVisible.value = true;
};

// create a new volume
const createVolumeVisble = ref(false);
const createVolumeRef = ref();
const createVolume = () => {
	createVolumeVisble.value = true;
};
const handleCreateVolume = () => {
	createVolumeRef.value.createVolume();
};

// change volume size
const changeVolumeSizeRef = ref();
const changeVolumeSizeVisible = ref(false);
const changeVolumeSize = () => {
	changeVolumeSizeVisible.value = true;
};
const handleChangeVolumeSize = () => {
	changeVolumeSizeRef.value.submitChange();
};

// delete volume
const delVolume = () => {
	let { currentRow } = toRefs(state.table);
	if (!currentRow.value) {
		ElMessage.warning(`请先选择要删除的存储卷`);
	} else {
		ElMessageBox.confirm(
			`确认删除存储卷：${currentRow.value?.rbdName}`,
			'删除存储卷',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			state.table.loading = true;
			useBlockStorageApi().delVolume({
				poolName: currentRow.value?.poolName,
				rbdName: currentRow.value?.rbdName
			}).then(() => {
				ElMessage.success(`添加【删除存储目录${currentRow.value?.rbdName}】任务成功`);
				tableRef.value.setCurrentRow();
			}).finally(() => {
				state.table.loading = false;
			});
		});
	}
};
</script>